# This is a sample Python script.
import os
import re
from pprint import pprint

import chardet as chardet

"""
userpreferencesasync.jx3dat 文件解析 false=勾选
Quest Trace =false, 任务追踪
Action Bar=false, 技能栏设置
Skill Guide=false, 武学助手
Video Setting=true,  镜头设置
HeadTop=true, 头顶血条
ChatPanel=true, 聊天栏设置 
UISeting=false, 界面常规设置 
Hotkey=false, 快捷键 
OnlineFrameAnchor=true 自定义界面位置
"""
logstr = ''
dir_path = os.getcwd()  # 运行当前目录
default_path = None
rolelist = []
mouldlist = []
old_role_file = ""
new_role_file = ""


# choicebox(msg=‘Pick an item’, title=‘’, choices=[], preselect=0, callback=None, run=True)
# print(full_userdata_dir)


def seach_roles(dirpath):
    full_userdata_dir = os.path.join(dirpath, 'userdata')
    if not os.path.exists(full_userdata_dir):
        return []
    dir_userdata = os.listdir(full_userdata_dir)
    # print(dir_userdata)
    l = []
    l2 = []
    rolecount = 0
    for i_username in dir_userdata:
        # print(i_username)
        fullpath_username = os.path.join(full_userdata_dir, i_username)
        if os.path.isdir(fullpath_username):
            # print(i_username)
            dir_username = os.listdir(fullpath_username)
            if 'login.ini' in dir_username:
                dict_username = {
                    'username': i_username,
                    'roles': [],
                }
                l.append(dict_username)
                for i_qufu in dir_username:
                    fullpath_qufu = os.path.join(fullpath_username, i_qufu)
                    if os.path.isdir(fullpath_qufu):
                        dir_qufu = os.listdir(fullpath_qufu)
                        # print(fullpath_username + '\t\t\t\t' + i_qufu)
                        for i_fwq in dir_qufu:
                            fullpath_fwq = os.path.join(fullpath_qufu, i_fwq)
                            if os.path.isdir(fullpath_fwq):
                                dir_fwq = os.listdir(fullpath_fwq)
                                if len(dir_fwq) > 0:
                                    # print(dir_fwq)
                                    rolecount += len(dir_fwq)
                                    dict_username['roles'] = dir_fwq
                                    # pprint(dict_username['roles'])
                                    for i_role in dir_fwq:
                                        fullpath_role = os.path.join(fullpath_fwq, i_role)
                                        if os.path.isdir(fullpath_role):
                                            roledict = {
                                                "qunum": i_qufu,
                                                "servername": i_fwq,
                                                "rolename": i_role,
                                                "sect": "",
                                                "wholepath": fullpath_role,
                                            }
                                            # 拿到每个角色的相关数据
                                            l2.append((i_role, i_username, i_qufu, i_fwq, "", fullpath_role))
                                            # l2.append(roledict) # 以字典形式存

    return l2


def get_role_datas():
    """
    获取角色数据文件，此时进入到角色命名的文件夹内了
    """
    result = None
    pass


def search_dirs(prefixpath, dirpath, signfile=None):
    full_path = os.path.join(prefixpath, dirpath)
    if not os.path.exists(full_path):
        return False
    if not os.path.isdir(full_path):
        return False
    files_list = os.listdir(full_path)
    if signfile in files_list:
        print(dirpath)
        return get_username_dir_list(os.path.join(full_path, signfile))
    return False


def search_roles(username_path, region, server=''):
    """
    获取角色信息（路径）
    """
    server_path = os.path.join(username_path, region, server)
    result = []
    if os.path.exists(server_path):
        roles_list = os.listdir(server_path)
        for role_name in roles_list:
            role_path = os.path.join(server_path, role_name)
            if os.path.isdir(role_path):
                role_dict = {
                    'role_name': role_name,
                    'role_path': role_path,
                    'role_sect': '',
                    'lenrole': len(os.listdir(role_path))
                }

                result.append(role_dict)
    return result
    pass


def get_user_region_server_rolescount(username_path, signfile=None):
    """
    通过rolenum.dat解析取得用户名下区、服、角色个数
    """
    if not signfile:
        return False
        pass
    sign_file_path = os.path.join(username_path, signfile)
    if not os.path.exists(sign_file_path):
        return False
    content = ''
    with open(sign_file_path, "r", errors='ignore') as f:
        content = f.read()
    # tmplist = re.findall(r'\{(.*?)\}', content.replace(" ","").replace("\n","").replace("\"",""))
    content = re.sub('[\s\"\[\]]', '', content)  # 去掉空格、tab、换行干扰，去掉[ 、 ]、"
    content_list = re.findall(r'\{(.*?)\}', re.sub('[\s\"\[\]]', '', content))[0].split(',')  # 匹配{}中的，然后以逗号分割
    if not content_list[0]:
        # print('没有数据' + rolenumpath)
        return False
    result = []
    for i in content_list:
        # print(re.split('[\\\=]', i))
        # region_and_server, count = re.split('[\\=]', i)
        region, server, count = re.split('[\\\=]', i)
        user_rolesnum_dict = {'region': region,
                              'server': server,
                              'count': count,
                              'roles': search_roles(username_path, region, server)}
        result.append(user_rolesnum_dict)

    # print(result)
    return result


def get_username_dir_list(prefixpath, filename='userdata'):
    """
    遍历userdata下用户名目录，找出有账号的用户名
    """
    fullpath = os.path.join(prefixpath, filename)
    if not os.path.exists(fullpath):
        return False
    useful_files_list = []
    files_list = os.listdir(fullpath)  # 这里列出的是用户名目录
    # 过滤出需要的
    for file in files_list:
        tdir = os.path.join(fullpath, file)
        file_list = get_user_region_server_rolescount(tdir, 'rolenum.dat')
        if file_list:
            useful_files_list.append({'username': file, 'user_role_data': file_list})
    # pprint(useful_files_list)
    return useful_files_list


def search_files(game_path):
    """
    暂不用
    """
    userdata_dir_path = os.path.join(game_path, 'userdata')  # 拼接：游戏路径/userdata
    if not os.path.exists(userdata_dir_path):
        return []
    username_files = os.listdir(userdata_dir_path)
    # 从userdata列出的用户名文件列表中遍历每个用户名下的文件
    for username_file in username_files:
        fullpath_username = os.path.join(userdata_dir_path, username_file)  # 拼接路径用户名
        if os.path.isdir(fullpath_username):
            # print(i_username)
            user_files = os.listdir(fullpath_username)
            if 'rolenum.dat' in user_files:
                # 表示这是一个正确的用户名，含有角色的目录
                # 然后开始遍历区目录
                # for i_qufu in dir_username:
                #     fullpath_qufu = os.path.join(fullpath_username, i_qufu)
                #     if os.path.isdir(fullpath_qufu):
                #         dir_qufu = os.listdir(fullpath_qufu)
                pass


# t = get_username_dir_list(r'D:\SeasunGame\Game\JX3\bin\zhcn_hd', 'userdata')
# print(t)

# tmppath = r'D:\SeasunGame\Game\JX3\bin\zhcn_hd\userdata\330247474@qq.com\rolenum.dat'
# print(get_user_region_server_rolescount(tmppath))
